package com.wyl.auth.service.impl;

import com.wyl.auth.bean.SseMessage;
import com.wyl.auth.common.service.RedisService;
import com.wyl.auth.exception.BusinessException;
import com.wyl.auth.service.SseService;
import com.wyl.auth.vo.RedisIndexVo;
import com.wyl.common.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2025/4/22 21:11
 */
@Slf4j
@Service
public class SseServiceImpl implements SseService {

    @Autowired
    private RedisService redisService;

    private static final Map<String,SseEmitter> concurrentMap = new ConcurrentHashMap<>();

    @Override
    public SseEmitter connect() {
        ResponseData responseData = new ResponseData<>();
        // 连接成功需要返回数据，否则会出现待处理状态
        SseEmitter sseEmitter = new SseEmitter();
        concurrentMap.put("sseEmitter",sseEmitter);
        try {
            responseData.setCode(200);
            RedisIndexVo redisIndexVo = redisService.getRedisIndex();
            responseData.setMsg("连接成功！");
            responseData.setData(redisIndexVo);
            sseEmitter.send(responseData, MediaType.APPLICATION_JSON);
        } catch (IOException e) {
            log.error("sse连接发送数据时出现异常：", e);
            throw new BusinessException("sse连接发送数据时出现异常！");
        }
        sseEmitter.onCompletion(() -> {
            log.info("sse连接断开");
        });

        sseEmitter.onTimeout(() -> {
            log.info("sse连接已超时");
        });

        sseEmitter.onError((throwable) -> {
            log.info("sse连接异常:", throwable);
        });

        return sseEmitter;
    }

    @Override
    public void activeSendMessage(SseMessage sseMessage) {

    }

    @Override
    public void sendMessage() {
        try {
            SseEmitter sseEmitter = concurrentMap.get("sseEmitter");
            if(sseEmitter == null) {
                return;
            }
            ResponseData responseData = new ResponseData();
            responseData.setCode(200);
            RedisIndexVo redisIndex = redisService.getRedisIndex();
            responseData.setData(redisIndex);
            sseEmitter.send(responseData, MediaType.APPLICATION_JSON);
        } catch (Exception e) {
            log.error("告警sse推送json转换异常：{}",  e);
        }
    }
}